
package event

import (
    "encoding/json"
	"github.com/looplab/fsm"
	"github.com/asaskevich/EventBus"
)

var (
	KernelBus       EventBus.Bus
)

func EventInit() {
	KernelBus = EventBus.New()
}

// 消息(事件)的通用消息头.
type MsgHeader struct {
	MsgType    string  `xml:"MsgType" json:"msg_type"`
	EventType  string  `xml:"Event"   json:"event"`
}

// 方法1： 定义消息(事件)的合集.
type MixedMsg struct {
	XMLName struct{}  `xml:"xml" json:"-"`
	MsgHeader
	CompanyId   int `xml:"CompanyId"  json:"company_id"`
	TradeInfo *struct {
		OrderId   int64 `xml:"OrderId"   json:"order_id"`
	} `xml:"TradeInfo,omitempty" json:"trade_info,omitempty"`
}

// 方法2：定义独立的结构,用interface来完成
type TradeMsg struct {
	XMLName struct{}  `xml:"xml" json:"-"`
	MsgHeader
	CompanyId int64   `xml:"CompanyId" json:"company_id"`
	UserId    int64   `xml:"UserId"    json:"user_id"`
	OrderId   int64 `xml:"OrderId"   json:"order_id"`
}

type ReturnMsg struct {
	XMLName struct{}    `xml:"xml" json:"-"`
	MsgHeader
	CompanyId    int    `xml:"CompanyId"    json:"company_id"`
	UserId       int    `xml:"UserId"       json:"user_id"`
	ReturnFormId string `xml:"ReturnFormId" json:"return_form_id"`
}

func EncodeMsg(request interface{}) (string, error) {
	body, err := json.Marshal(request)
	if err != nil {
		return "", err
	}
	return string(body), nil
}

func DecodeMsg(input string, response interface{}) (string, error) {
	if response != nil {
		return input, json.Unmarshal([]byte(input), &response)
	}
	return input, nil
}

type StateMachine struct {
	Name  string  `json:"name"`
	Src   string  `json:"src"`
	Dst   string  `json:"dst"`
}
type Fsm struct{
    StateMachines []StateMachine `json:"fsm"`
}

func GetFsmStateByJson(jsonState string)(fsm.Events, error) {
    fsmEvents := fsm.Events{}
	fsmTmp := Fsm{}
    err := json.Unmarshal([]byte(jsonState), &fsmTmp)
    if err != nil {
		//beego.Debug("GetFsmStateByJson err: ", err.Error())
		return fsmEvents, err
	}
	//beego.Debug("GetFsmStateByJson: ", jsonState)
    for _, item:= range fsmTmp.StateMachines {
		var src []string
		src = append(src, item.Src)
	    eventDesc := fsm.EventDesc{Name:item.Name,Src:src,Dst:item.Dst}
		fsmEvents = append(fsmEvents, eventDesc)
	}
    return fsmEvents, nil
}
